<template>
	<view class="content">
		<!-- #ifdef APP-PLUS || H5 -->
		<view class="scene-container">
			<view id="container"></view>
			<view class="overlay">
				<view class="info-card">
					<text class="card-title">智慧医院实时监控</text>
					<view class="card-content">
						<view class="stat-item">
							<text class="stat-value">358</text>
							<text class="stat-label">在线人数</text>
						</view>
						<view class="stat-item warning">
							<text class="stat-value">12</text>
							<text class="stat-label">告警数量</text>
						</view>
						<view class="stat-item success">
							<text class="stat-value">100%</text>
							<text class="stat-label">设备状态</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- #endif -->
		<!-- #ifndef APP-PLUS || H5 -->
		<view class="unsupported">
			<u-icon name="info-circle" size="48" color="#909399"></u-icon>
			<text class="unsupported-text">非 APP、H5 环境支持</text>
		</view>
		<!-- #endif -->
	</view>
</template>

<script module="Cesium" lang="renderjs">
	export default {
		data() {
			return {
				viewer: null,
				domlist: null,
			}
		},
		mounted() {
			this.initResources()
		},
		methods: {
			initResources() {
				if (this.domlist) {
					this.removeResource()
				} else {
					const linkDom = document.createElement('link')
					linkDom.rel = "stylesheet"
					linkDom.href = "https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Widgets/widgets.css"
					document.head.appendChild(linkDom)

					var cesiumS = this.requireResources('script', 'https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Cesium.js', this.initCesium)
					this.domlist = [linkDom, cesiumS]
				}
			},
			requireResources(dom, src, callback) {
				const script = document.createElement(dom)
				script.src = src
				document.head.appendChild(script)
				callback && (callback instanceof Function) && (script.onload = callback.bind(this))
				return script
			},
			removeResource() {
				if (this.domlist)
					for (let i = 0; i < this.domlist.length; i++) {
						document.head.removeChild(this.domlist[i])
					}
			},
			initCesium() {
				// 使用新的 token
				Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5YzM3MmM4YS02ZWM0LTRhOGUtOTZhZS1jOWJmMjkwNmE3YTYiLCJpZCI6MTgwMTIzLCJpYXQiOjE3MDE4MjQ3Mjh9.oq5DL_Mz9kXTvoRJnEgJXxkwGEHzzw-qkv9uuWUVqOU';

				// 创建 OpenStreetMap 影像提供者
				const imageryProvider = new Cesium.OpenStreetMapImageryProvider({
					url: 'https://a.tile.openstreetmap.org/',
					credit: '© OpenStreetMap contributors',
					maximumLevel: 18
				});

				// 初始化viewer
				this.viewer = new Cesium.Viewer('container', {
					animation: false,
					baseLayerPicker: false,
					fullscreenButton: false,
					geocoder: false,
					homeButton: false,
					navigationHelpButton: false,
					sceneModePicker: false,
					timeline: false,
					scene3DOnly: true,
					imageryProvider: imageryProvider,
					requestRenderMode: false,
					msaaSamples: 8, // 增加MSAA采样级别
					infoBox: false, // 禁用信息框
					selectionIndicator: false, // 禁用选择指示器
					contextOptions: {
						webgl: {
							alpha: false,
							depth: true,
							stencil: false,
							antialias: true,
							premultipliedAlpha: true,
							preserveDrawingBuffer: false,
							failIfMajorPerformanceCaveat: false
						}
					}
				});

				// 移除默认的底部版权信息
				this.viewer._cesiumWidget._creditContainer.style.display = 'none';

				// 设置场景效果
				const scene = this.viewer.scene;

				// 优化光照和渲染质量
				scene.globe.enableLighting = false; // 关闭动态光照
				scene.globe.baseColor = Cesium.Color.WHITE; // 设置地球基色为白色
				scene.globe.atmosphereBrightnessShift = 0.6; // 调整大气亮度
				scene.globe.atmosphereSaturationShift = 1.0; // 调整大气饱和度
				scene.globe.atmosphereHueShift = 0.0; // 调整大气色调

				// 设置默认光源
				scene.light = new Cesium.DirectionalLight({
					direction: new Cesium.Cartesian3(0.5, 0.5, -1.0), // 光照方向
					intensity: 2.0, // 增加光照强度
					color: new Cesium.Color(1.0, 1.0, 1.0, 1.0) // 白色光源
				});

				// 移除环境光设置
				// scene.lightSource.ambientLightColor = new Cesium.Color(0.3, 0.3, 0.3, 1.0);

				// 设置全局光照
				scene.globe.enableLighting = true;
				scene.globe.lambertDiffuseMultiplier = 2.5; // 增加漫反射强度
				scene.globe.specularPower = 16.0; // 调整镜面反射

				// 优化渲染质量
				scene.postProcessStages.fxaa.enabled = true;
				scene.fxaa = true;
				scene.fog.enabled = false;

				// 优化分辨率和渲染质量
				scene.globe.maximumScreenSpaceError = 1.0; // 降低屏幕空间误差
				scene.globe.tileCacheSize = 1000; // 增加瓦片缓存
				// 移除 tileLoadProgressEvent 设置
				scene.globe.terrainExaggeration = 1.0; // 设置地形夸张程度
				scene.globe.baseColor = Cesium.Color.WHITE; // 设置基础颜色

				// 设置渲染参数
				scene.globe.maximumSimultaneousTileLoads = 20; // 同时加载的瓦片数量
				scene.globe.tileCacheSize = 1000; // 瓦片缓存大小
				scene.globe.loadingDescendantLimit = 20; // 限制同时加载的子瓦片数量
				scene.globe.preloadSiblings = false; // 禁用兄弟瓦片预加载
				scene.globe.preferLeaves = true; // 优先加载叶子节点

				// 设置分辨率自适应
				const resolutionScale = window.devicePixelRatio || 1.0;
				scene.pixelRatio = resolutionScale;

				// 加载3D Tiles
				this.loadTileset().then((tileset) => {
					if (tileset) {
						// 获取tileset的边界球
						const boundingSphere = tileset.boundingSphere;

						// 设置初始远距离视角
						const offset = new Cesium.HeadingPitchRange(0, -0.5, boundingSphere.radius * 15);
						this.viewer.camera.lookAt(boundingSphere.center, offset);

						// 开始飞行动画
						setTimeout(() => {
							this.flyToTileset(boundingSphere);
						}, 1000);
					}
				});
			},

			// 添加新的方法用于加载3D Tiles
			async loadTileset() {
				try {
					const tileset = new Cesium.Cesium3DTileset({
						url: 'http://47.94.229.196:90/YLY3DTiles/tileset.json',
						maximumScreenSpaceError: 1.0,
						maximumMemoryUsage: 4096,
						luminanceAtZenith: 0.2, // 调整天顶亮度
						imageBasedLightingFactor: new Cesium.Cartesian2(1.5, 1.5), // 增加基于图像的光照因子
						lightColor: new Cesium.Cartesian3(1.5, 1.5, 1.5), // 增加光照颜色
						preferLeaves: true,
						dynamicScreenSpaceError: true,
						dynamicScreenSpaceErrorDensity: 0.00278,
						dynamicScreenSpaceErrorFactor: 4.0,
						dynamicScreenSpaceErrorHeightFalloff: 0.25,
						skipLevelOfDetail: false, // 禁用跳过细节层次
						baseScreenSpaceError: 1024,
						skipScreenSpaceErrorFactor: 16,
						skipLevels: 0, // 跳过层级
						immediatelyLoadDesiredLevelOfDetail: true,
						loadSiblings: false,
						cullWithChildrenBounds: true,

						maximumSimultaneousTileLoads: 20,
						maximumCachedBytes: 256 * 1024 * 1024,
						preloadWhenHidden: true,
						progressiveResolutionHeightFraction: 0.1, // 渐进式分辨率
						foveatedScreenSpaceError: true, // 启用中心区域高清
						foveatedConeSize: 0.1,
						foveatedMinimumScreenSpaceErrorRelaxation: 0.0,
						foveatedInterpolationCallback: undefined,
						foveatedTimeDelay: 0.2
					});

					await tileset.readyPromise;
					this.viewer.scene.primitives.add(tileset);

					// 调整材质
					tileset.style = new Cesium.Cesium3DTileStyle({
						color: 'color("white", 1.0)', // 增加模型亮度
						show: true
					});

					// 优化渲染
					tileset.maximumMemoryUsage = 4096;
					tileset.preloadFlightDestinations = true;
					tileset.preferLeaves = true;
					tileset.dynamicScreenSpaceError = true;

					console.log('3D Tiles loaded successfully');
					return tileset;
				} catch (error) {
					console.error('Failed to load 3D Tiles:', error);
					uni.showToast({
						title: '模型加载失败',
						icon: 'none'
					});
					return null;
				}
			},

			// 添加新的飞行方法
			async flyToTileset(boundingSphere) {
				// 飞向模型，将 radius * 0.348 改为 radius * 1.044 (0.348 * 3)
				this.viewer.camera.flyToBoundingSphere(boundingSphere, {
					duration: 5,
					offset: new Cesium.HeadingPitchRange(0, -0.5, boundingSphere.radius * 1.044),
					complete: () => {
						// 飞行完成后开始缓慢旋转
						this.startRotation(boundingSphere);
					}
				});
			},

			// 添加旋转动画方法
			startRotation(boundingSphere) {
				let rotationAngle = 0;
				let lastTime = performance.now();

				const animate = () => {
					const currentTime = performance.now();
					const deltaTime = currentTime - lastTime;
					lastTime = currentTime;

					// 保持相同的旋转速度
					rotationAngle += (0.000785 * deltaTime) / 16.67;

					this.viewer.camera.lookAt(
						boundingSphere.center,
						new Cesium.HeadingPitchRange(
							rotationAngle,
							-0.5,
							boundingSphere.radius * 1.044  // 这里也改为 1.044
						)
					);

					requestAnimationFrame(animate);
				};

				animate();
			},

			addBuildingLabels() {
				const floors = ['急诊部', '门诊部', '住院部', 'ICU'];
				floors.forEach((floor, index) => {
					this.viewer.entities.add({
						position: Cesium.Cartesian3.fromDegrees(121.002, 31.002, 20 * (index + 1)),
						label: {
							text: floor,
							font: '24px sans-serif',
							fillColor: Cesium.Color.WHITE,
							outlineColor: Cesium.Color.BLACK,
							outlineWidth: 2,
							style: Cesium.LabelStyle.FILL_AND_OUTLINE,
							verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
							pixelOffset: new Cesium.Cartesian2(0, -10)
						}
					});
				});
			}
		},
		beforeDestroy() {
			this.removeResource()
			if (this.viewer) {
				this.viewer.destroy();
			}
		}
	}
</script>

<style>
	.content {
		width: 100vw;
		height: 100vh;
		position: relative;
		background: linear-gradient(to bottom, #2980B9, rgba(41, 128, 185, 0.8));
	}

	.scene-container {
		width: 100%;
		height: 100%;
		position: relative;
	}

	#container {
		width: 100%;
		height: 100%;
		background: linear-gradient(135deg, #2980B9, rgba(127, 255, 212, 0.1));
	}

	.overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		pointer-events: none;
		padding: 40rpx;
	}

	.info-card {
		background: rgba(41, 128, 185, 0.85);
		backdrop-filter: blur(12px);
		border-radius: 24rpx;
		padding: 36rpx;
		color: #E0FFFF;
		max-width: 600rpx;
		border: 2px solid rgba(127, 255, 212, 0.3);
		box-shadow: 0 8px 32px rgba(41, 128, 185, 0.4);
		position: relative;
		overflow: hidden;
	}

	.info-card::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, rgba(127, 255, 212, 0.1), transparent);
		pointer-events: none;
	}

	.card-title {
		font-size: 36rpx;
		font-weight: 600;
		margin-bottom: 36rpx;
		display: block;
		color: #E0FFFF;
		letter-spacing: 4px;
		text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		text-align: center;
		position: relative;
	}

	.card-title::after {
		content: '';
		position: absolute;
		bottom: -10rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background: #7FFFD4;
		border-radius: 2rpx;
	}

	.card-content {
		display: flex;
		justify-content: space-between;
		gap: 24rpx;
	}

	.stat-item {
		flex: 1;
		text-align: center;
		background: rgba(255, 255, 255, 0.1);
		padding: 24rpx;
		border-radius: 16rpx;
		transition: all 0.4s ease;
		border: 1px solid rgba(127, 255, 212, 0.2);
		position: relative;
		overflow: hidden;
	}

	.stat-item::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, rgba(127, 255, 212, 0.1), transparent);
		opacity: 0;
		transition: opacity 0.4s ease;
	}

	.stat-item:hover::before {
		opacity: 1;
	}

	.stat-item.warning {
		border-color: rgba(255, 215, 0, 0.3);
	}

	.stat-item.success {
		border-color: rgba(127, 255, 212, 0.3);
	}

	.stat-value {
		font-size: 42rpx;
		font-weight: bold;
		display: block;
		margin-bottom: 12rpx;
		color: #E0FFFF;
		text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		position: relative;
		z-index: 1;
	}

	.stat-item.warning .stat-value {
		color: #FFD700;
	}

	.stat-item.success .stat-value {
		color: #7FFFD4;
	}

	.stat-label {
		font-size: 26rpx;
		opacity: 0.95;
		color: #E0FFFF;
		font-weight: 500;
		position: relative;
		z-index: 1;
	}

	@keyframes pulse {
		0% {
			box-shadow: 0 0 0 0 rgba(41, 128, 185, 0.4);
		}
		70% {
			box-shadow: 0 0 0 20rpx rgba(41, 128, 185, 0);
		}
		100% {
			box-shadow: 0 0 0 0 rgba(41, 128, 185, 0);
		}
	}

	.stat-item {
		animation: pulse 3s infinite;
	}

	.stat-item.warning {
		animation: warningPulse 3s infinite;
	}

	@keyframes warningPulse {
		0% {
			box-shadow: 0 0 0 0 rgba(255, 215, 0, 0.4);
		}
		70% {
			box-shadow: 0 0 0 20rpx rgba(255, 215, 0, 0);
		}
		100% {
			box-shadow: 0 0 0 0 rgba(255, 215, 0, 0);
		}
	}

	.stat-item.success {
		animation: successPulse 3s infinite;
	}

	@keyframes successPulse {
		0% {
			box-shadow: 0 0 0 0 rgba(127, 255, 212, 0.4);
		}
		70% {
			box-shadow: 0 0 0 20rpx rgba(127, 255, 212, 0);
		}
		100% {
			box-shadow: 0 0 0 0 rgba(127, 255, 212, 0);
		}
	}

	.unsupported {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 20rpx;
		background: #1a1a1a;
		color: #909399;
	}

	.unsupported-text {
		font-size: 28rpx;
	}

	/* Cesium 默认控件样式覆盖 */
	:deep(.cesium-viewer-toolbar),
	:deep(.cesium-viewer-timelineContainer),
	:deep(.cesium-viewer-animationContainer),
	:deep(.cesium-viewer-fullscreenContainer) {
		display: none;
	}

	:deep(.cesium-viewer-bottom) {
		display: none;
	}

	/* 添加医疗主题的图标背景 */
	.info-card::before {
		content: '';
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		width: 40rpx;
		height: 40rpx;
		background: rgba(255, 255, 255, 0.1);
		border-radius: 50%;
		opacity: 0.5;
	}

	/* 添加脉冲动画效果 */
	@keyframes pulse {
		0% {
			box-shadow: 0 0 0 0 rgba(41, 128, 185, 0.4);
		}
		70% {
			box-shadow: 0 0 0 10px rgba(41, 128, 185, 0);
		}
		100% {
			box-shadow: 0 0 0 0 rgba(41, 128, 185, 0);
		}
	}

	.stat-item {
		animation: pulse 2s infinite;
	}
</style>


















